package com.dgut.service.background.controller;

import com.alibaba.fastjson.JSON;
import com.dgut.service.background.config.resultConfig.JsonResult;
import com.dgut.service.background.config.resultConfig.ResultTool;
import com.dgut.service.background.entity.User;
import com.dgut.service.background.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * 用户
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //获取所有用户分页
    @GetMapping("allUser/{page}")
    public String allUser(@PathVariable("page") int page){
        Page<User> users = userService.findAllUser(page);
        JsonResult result = ResultTool.success(users);
        return JSON.toJSONString(result);
    }

    //按id查找用户
    @GetMapping("userId/{userId}")
    public String findByUserId(@PathVariable("userId") int userId){
        User user = userService.findByUserId(userId);
        JsonResult result = ResultTool.success(user);
        return JSON.toJSONString(result);
    }

    //按id删除用户
    @DeleteMapping("userId/{userId}")
    public String deleteOneUser(@PathVariable("userId") int userId){
        userService.deleteOneUser(userId);
        JsonResult result = ResultTool.success();
        return JSON.toJSONString(result);
    }

    //按姓名查找用户分页
    @GetMapping("userName/{userName}/{page}")
    public String findByUserName(@PathVariable("userName") String userName, @PathVariable("page") int page){
        Page<User> users = userService.findByUserName(userName,page);
        JsonResult result = ResultTool.success(users);
        return JSON.toJSONString(result);
    }

    @PostMapping("oneUser")
    public String saveOneUser(User user){
        userService.saveOneUser(user);
        JsonResult result = ResultTool.success();
        return JSON.toJSONString(result);
    }

    @GetMapping("openId/{openId}")
    public String findByOpenId(@PathVariable("openId")String openId){
        User user = userService.findByOpenId(openId);
        JsonResult result = ResultTool.success(user);
        return JSON.toJSONString(result);
    }
}
